import axios from "axios";

export default {
    data() {
        return {
            src: null,
            filePreviewRef: null,
            excelOptions: {
                xls: this.fileType !== "xlsx", // Preview xlsx files as false; preview xls files as true
                minColLength: 0, // Minimum number of columns to render, set to 0 to render based on content
                minRowLength: 0, // Minimum number of rows to render, set to 0 to render based on content
                widthOffset: 10, // Add extra width (in pixels) to the default rendered cell width
                heightOffset: 10, // Add extra height (in pixels) to the default rendered cell height
                beforeTransformData: workbookData => workbookData, // Modify the Excel workbook data before rendering
                transformData: workbookData => workbookData // Modify the Excel workbook data before displaying
            }
        };
    },
    props: {
        id: {
            type: [String, Number],
            default: null
        },
        type: {
            type: String,
            default: ""
        },
        fileType: {
            type: String,
            default: ""
        },
        raw: {
            type: File,
            default: () => new File([], "")
        },
        filePath: {
            type: String,
            default: ""
        }
    },
    mounted() {
        this.renderTheFile(); // Call the file render function on component mount
    },
    methods: {
        /**
         * Handle file rendering success
         */
        renderedHandler() {
            console.log("File rendered successfully");
        },
        /**
         * Handle file rendering error
         * @param {Error} e
         */
        errorHandler(e) {
            console.log("File render failed", e);
        },
        /**
         * Render the file
         */
        async renderTheFile() {
            if (this.type === "local") {
                console.log("Local file type: " + this.fileType);
                this.isImage(this.fileType) && this.localImagePreview(this.raw);
                this.isDoc(this.fileType) && this.localOfficePreview(this.raw);
                this.isText(this.fileType) && this.localTextPreview(this.raw);
                this.isVideo(this.fileType) && this.localVideoPreview(this.raw);
                this.isAudio(this.fileType) && this.localAudioPreview(this.raw);
            } else {
                if (this.isVideo(this.fileType)) {
                    this.src =
                        process.env.VUE_APP_BASE_URL +
                        "/upload/attachments/getTeamOfVideo?id=" +
                        this.id;
                    return;
                }
                if (this.isText(this.fileType)) {
                    const response = await axios.get(
                        process.env.VUE_APP_STATIC_URL + this.filePath,
                        { responseType: "text" }
                    );
                    this.src = response.data;
                    return;
                }
                this.src = process.env.VUE_APP_STATIC_URL + this.filePath;
            }
        },
        // Validate if the file is an image
        isImage(type) {
            const types = [
                "jpg",
                "png",
                "gif",
                "jpeg",
                "bmp",
                "webp",
                "svg",
                "tiff",
                "tif",
                "jfif",
                "pjpeg",
                "pjp"
            ];
            return types.includes(type);
        },
        // Validate if the file is a document
        isDoc(type) {
            const types = ["docx", "doc", "xlsx", "xls", "pdf"];
            return types.includes(type);
        },
        // Validate if the file is a text file
        isText(type) {
            const types = [
                "txt",
                "md",
                "log",
                "json",
                "xml",
                "html",
                "css",
                "js",
                "java",
                "c",
                "cpp",
                "h",
                "hpp",
                "py",
                "rb",
                "go",
                "sh",
                "bat",
                "ps1"
            ];
            return types.includes(type);
        },
        // Validate if the file is a video
        isVideo(type) {
            const types = [
                "mp4",
                "avi",
                "rmvb",
                "mkv",
                "flv",
                "wmv",
                "mov",
                "webm",
                "m4v",
                "mpg",
                "mpeg",
                "3gp",
                "vob"
            ];
            return types.includes(type);
        },
        // Validate if the file is an audio file
        isAudio(type) {
            const types = ["mp3", "wav", "ogg", "flac", "aac", "wma", "m4a"];
            return types.includes(type);
        },
        // Local preview for Office files
        localOfficePreview(file) {
            const reader = new FileReader();
            reader.readAsArrayBuffer(file);
            reader.onload = loadEvent => {
                const arrayBuffer = loadEvent.target.result;
                const blob = new Blob([arrayBuffer], {
                    type:
                        "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                });
                this.src = URL.createObjectURL(blob);
            };
        },
        // Local preview for images
        localImagePreview(file) {
            const reader = new FileReader();
            reader.onload = e => {
                this.src = e.target.result;
            };
            reader.readAsDataURL(file);
        },
        // Local preview for text files
        localTextPreview(file) {
            const reader = new FileReader();
            reader.onload = e => {
                this.src = e.target.result;
            };
            reader.readAsText(file);
        },
        // Local preview for videos
        localVideoPreview(file) {
            this.src = URL.createObjectURL(file);
        },
        // Local preview for audio files
        localAudioPreview(file) {
            const reader = new FileReader();
            reader.onloadend = () => {
                const blob = new Blob([reader.result], { type: "audio/mpeg" });
                this.src = URL.createObjectURL(blob);
            };
            reader.readAsArrayBuffer(file);
        }
    },
    beforeDestroy() {
        // Cleanup when component is destroyed
        if (this.src) {
            if (this.isVideo(this.fileType) || this.isAudio(this.fileType)) {
                URL.revokeObjectURL(this.src);
            }
        }
    }
};
